package com.zjl.litemall.admin.shiro;


import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import com.zjl.litemall.core.util.bcrypt.BCryptPasswordEncoder;
import com.zjl.litemall.db.domain.LitemallAdmin;
import com.zjl.litemall.db.service.LitemallAdminService;
import com.zjl.litemall.db.service.LitemallPermissionService;
import com.zjl.litemall.db.service.LitemallRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Set;

/**
 * 下面三个Autowired注解需要配合Lazy注解使用，否则会导致这三个service相关的事务失效。
 * https://gitee.com/linlinjava/litemall/issues/I3I94X#note_4809495
 */

/**
 * shiro中自定义realm一般继承AuthorizingRealm，然后实现getAuthenticationInfo和getAuthorizationInfo方法，来完成登录和权限的验证。

 GetAuthorizationInfo
 该方法主要是用于当前登录用户授权。
 1. 调用SecurityUtils.getSubject().isPermitted(String str)方法时会调用。
 2. 在@Controller 上@RequiresRoles("admin")在方法上加注解的时候调用
 3. [@shiro.hasPermission name = "admin"][/@shiro.hasPermission]或者
 <shiro:hasPermission name="admin"></shiro:hasPermission>在页面上加shiro标签的时候，即进这个页面的时候扫描到有这个标签的时候调用

 GetAuthenticationInfo
 该方法是进行用户验证的。调用currUser.login(token)方法时会调用doGetAuthenticationInfo方法。
 */
public class AdminAuthorizingRealm extends AuthorizingRealm {

    @Autowired
    @Lazy
    private LitemallAdminService adminService;
    @Autowired
    @Lazy
    private LitemallRoleService roleService;
    @Autowired
    @Lazy
    private LitemallPermissionService permissionService;

    /**
     * @description 授权
     * 根据PrincipalCollection，获得当前登陆管理员，获得角色。
     * 根据角色，获得角色的name字段和permission字段。
     *
     * @updateTime 2022/3/19 下午6:41
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        if (principals == null) {
            throw new AuthorizationException("PrincipalCollection method argument cannot be null.");
        }
        // 获得管理员信息
        LitemallAdmin admin = (LitemallAdmin) getAvailablePrincipal(principals);

        Integer[] roleIds = admin.getRoleIds();
        // 查litemall_role表，得到所有角色的name字段
        Set<String> roles = roleService.queryByIds(roleIds);
        // 查litemall_permission表，得到所有角色的permission字段
        Set<String> permissions = permissionService.queryByRoleIds(roleIds);

        // org.apache.shiro.authz.SimpleAuthorizationInfo
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(roles);
        info.setStringPermissions(permissions);

        return info;
    }

    /**
     * @description 认证

     * @updateTime 2022/3/19 下午6:36
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        String username = upToken.getUsername();
        String password = new String(upToken.getPassword());

        if (StringUtils.isEmpty(username)) {
            throw new AccountException("用户名不能为空");
        }
        if (StringUtils.isEmpty(password)) {
            throw new AccountException("密码不能为空");
        }

        List<LitemallAdmin> adminList = adminService.findAdmin(username);
        Assert.state(adminList.size() < 2, "同一个用户名存在两个账户");
        if (adminList.size() == 0) {
            throw new UnknownAccountException("找不到用户（" + username + "）的帐号信息");
        }
        LitemallAdmin admin = adminList.get(0);

        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if (!encoder.matches(password, admin.getPassword())) {
            throw new UnknownAccountException("找不到用户（" + username + "）的帐号信息");
        }

        return new SimpleAuthenticationInfo(admin, password, getName());
    }

}
